package com.dsr.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.dsr.consts.PageResult;
import com.dsr.consts.Result;
import com.dsr.consts.e.UserProperty;
import com.dsr.dao.ShopDao;
import com.dsr.entity.Shop;
import com.dsr.exception.FlowerException;
import com.dsr.service.ShopService;
import com.dsr.util.BasicUtil;
import com.dsr.util.IdWorker;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * (Shop)表服务实现类
 *
 * @author dsr
 * @since 2020-10-08
 */
@Service("shopService")
public class ShopServiceImpl implements ShopService {
    @Autowired
    private ShopDao shopDao;
    @Autowired
    private IdWorker idWorker;

    @Override
    public Result save(Shop shop) {
        String userId = BasicUtil.getToken(UserProperty.USER_ID);
        if(StringUtils.isEmpty(userId)){
            throw new FlowerException(HttpStatus.NETWORK_AUTHENTICATION_REQUIRED,"登录失效");
        }
        Shop isExist = shopDao.queryIsExist(userId, shop.getFlowerId());
        if (isExist != null) {
            isExist.setNumber(shop.getNumber() + isExist.getNumber());
            shopDao.updateByPrimaryKeySelective(isExist);
        } else {
            shop.setDateTime(DateTime.now());
            shop.setUserId(userId);
            shop.setId(String.valueOf(idWorker.nextId()));
            shopDao.insertSelective(shop);
        }
        return Result.success("保存成功");
    }

    @Override
    public Result update(Shop shop) {
        shopDao.updateByPrimaryKeySelective(shop);
        return Result.success("修改成功");
    }

    @Override
    public Result delete(String id) {
        if (StringUtils.isNotEmpty(id)) {
            List<String> ids = Arrays.asList(id.split(","));
            Example example = new Example(Shop.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andIn("id", ids);
            shopDao.deleteByExample(example);
            return Result.success("删除成功");
        }
        return Result.error("请选择要删除的行");
    }


    @Override
    public Result list() {
        String userId = BasicUtil.getToken(UserProperty.USER_ID);
        if(StringUtils.isEmpty(userId)){
            return Result.success(new ArrayList<>());
        }
        return Result.success(shopDao.queryShops(userId));
    }
}